package com.jxstyle.modular.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxstyle.core.base.BaseController;
import com.jxstyle.core.common.Constant;
import com.jxstyle.core.common.page.PageInfo;
import com.jxstyle.core.util.PasswordUtil;
import com.jxstyle.modular.entity.User;
import com.jxstyle.modular.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	private final String prefix = "/user";
	@Autowired
	private UserService userService;
	@Autowired
	private PasswordUtil passwordUtil;
	
	@GetMapping(value = "")
	public String userpage() {
		return prefix + "/list";
	}

	@GetMapping(value = "/add")
	public String add() {
		return prefix + "/add";
	}

	@GetMapping(value = "/edit/{id}")
	public String edit(@PathVariable int id, ModelMap modelMap) {
		modelMap.put("id", id);
		return prefix + "/edit";
	}

	@GetMapping(value = "/set/{id}")
	public String set(@PathVariable int id, ModelMap modelMap) {
		modelMap.put("id", id);
		return prefix + "/set";
	}

	@ResponseBody
	@PostMapping(value = "/add")
	public Boolean add(User user) {
		user.setPassword(passwordUtil.encode(Constant.DEFAULT_PASSWORD));
		userService.save(user);
		return true;
	}

	@ResponseBody
	@PostMapping(value = "/edit")
	public Boolean edit(User user) {
		userService.updateById(user);
		return true;
	}

	@ResponseBody
	@PostMapping(value = "/delete/{id}")
	public Boolean delete(@PathVariable int id) {
		userService.removeById(id);
		return true;
	}

	@ResponseBody
	@GetMapping(value = "/get/{id}")
	public User get(@PathVariable int id) {
		User user = userService.getById(id);
		return user;
	}

	@ResponseBody
	@PostMapping("")
	public PageInfo<User> page(PageInfo<User> page) {
		QueryWrapper<User> wrapper = new QueryWrapper<>();
		wrapper.orderByDesc("regist_time");
		return userService.page(page, wrapper);
	}

}
